<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="司机姓名" prop="driverName">
        <el-input
          v-model="queryParams.driverName"
          placeholder="请输入司机姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="driverPhone">
        <el-input
          v-model="queryParams.driverPhone"
          placeholder="请输入司机手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['driver:driver:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['driver:driver:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['driver:driver:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['driver:driver:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="driverList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="身份证号" align="center" prop="card" />
      <el-table-column label="司机姓名" align="center" prop="driverName" />
      <el-table-column label="司机性别" align="center" prop="driverSex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gender" :value="scope.row.driverSex" />
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="driverPhone" />
      <el-table-column
        label="注册时间"
        align="center"
        prop="registrationTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.registrationTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="城市" align="center" prop="cityId" /> -->
      <el-table-column label="绑定车辆" align="center" prop="model" />
      <el-table-column label="车辆级别" align="center" prop="levelName" />
      <el-table-column label="司机状态" align="center" prop="driverStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.driver_status"
            :value="scope.row.driverStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center" prop="workStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.work_status"
            :value="scope.row.workStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="司机主管" align="center" prop="userName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <!-- 在操作列的template中添加审批按钮 -->
        <template slot-scope="scope">
          <!-- 现有按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['driver:driver:detail']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['driver:driver:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-unlock"
            @click="handleUnfreeze(scope.row)"
            v-hasPermi="['driver:driver:unfreeze']"
            >解冻</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-unlink"
            @click="handleTerminate(scope.row)"
            v-hasPermi="['driver:driver:terminate']"
            v-if="scope.row.driverStatus == 0"
            >解约</el-button
          >
          <!-- 添加审批按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleApprove(scope.row)"
            v-hasPermi="['driver:driver:approve']"
            >审批</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改司机管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="司机性别" prop="driverSex">
          <el-select v-model="form.driverSex" placeholder="请选择司机性别">
            <el-option
              v-for="dict in dict.type.gender"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="司机姓名" prop="driverName">
          <el-input v-model="form.driverName" placeholder="请输入司机姓名" />
        </el-form-item>

        <el-form-item label="身份证号" prop="card">
          <el-input v-model="form.card" placeholder="请输入身份证号码" />
        </el-form-item>
        <el-form-item label="手机号码" prop="driverPhone">
          <el-input
            v-model="form.driverPhone"
            placeholder="请输入司机手机号码"
          />
        </el-form-item>

        <el-form-item label="车辆级别" prop="vehicleLevel">
          <el-input v-model="form.vehicleLevel" placeholder="请输入车辆级别" />
        </el-form-item>
        <el-form-item label="司机状态" prop="driverStatus">
          <el-select v-model="form.driverStatus" placeholder="请选择司机状态">
            <el-option
              v-for="dict in dict.type.driver_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前状态" prop="workStatus">
          <el-radio-group v-model="form.workStatus">
            <el-radio
              v-for="dict in dict.type.work_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="有效期起" prop="contractStartDate">
          <el-date-picker
            clearable
            v-model="form.contractStartDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择合同有效期起"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期止" prop="contractEndDate">
          <el-date-picker
            clearable
            v-model="form.contractEndDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择合同有效期止"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <!-- 在template标签末尾添加审批弹窗 -->
      <!-- 审批对话框 -->
      <el-dialog
        title="司机审批"
        :visible.sync="approveDialog"
        width="500px"
        append-to-body
      >
        <el-form
          ref="approveForm"
          :model="approveForm"
          :rules="approveRules"
          label-width="80px"
        >
          <el-form-item label="司机姓名" disabled>
            <el-input v-model="approveForm.driverName" readonly />
          </el-form-item>
          <el-form-item label="审批结果" prop="approveStatus">
            <el-radio-group v-model="approveForm.approveStatus">
              <el-radio label="0">审批通过</el-radio>
              <el-radio label="1">审批拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审批原因" prop="approveReason">
            <el-input
              v-model="approveForm.approveReason"
              type="textarea"
              placeholder="请输入审批原因"
              :rows="4"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="approveDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitApprove">确 定</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDriver,
  getDriver,
  delDriver,
  addDriver,
  updateDriver,
  updateDriverStatus,
} from "@/api/driver/driver";

// 在data()中添加审批相关数据
export default {
  name: "Driver",
  dicts: ["work_status", "gender", "driver_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 司机管理表格数据
      driverList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        driverName: null,
        driverPhone: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        driverName: [
          { required: true, message: "司机姓名不能为空", trigger: "blur" },
        ],
        driverSex: [
          { required: true, message: "司机性别不能为空", trigger: "change" },
        ],
        driverPhone: [
          { required: true, message: "司机手机号码不能为空", trigger: "blur" },
        ],
        registrationTime: [
          { required: true, message: "注册时间不能为空", trigger: "blur" },
        ],
        cityId: [
          { required: true, message: "城市ID不能为空", trigger: "change" },
        ],
        bindVehicle: [
          { required: true, message: "绑定车辆不能为空", trigger: "change" },
        ],
        vehicleLevel: [
          { required: true, message: "车辆级别不能为空", trigger: "blur" },
        ],
        driverStatus: [
          { required: true, message: "司机状态不能为空", trigger: "change" },
        ],
        workStatus: [
          { required: true, message: "工作状态不能为空", trigger: "change" },
        ],
        userId: [
          { required: true, message: "司机主管不能为空", trigger: "change" },
        ],
        card: [
          { required: true, message: "身份证号码不能为空", trigger: "blur" },
        ],
        contractStartDate: [
          {
            required: true,
            message: "合同(或协议)有效期起不能为空",
            trigger: "blur",
          },
        ],
        contractEndDate: [
          {
            required: true,
            message: "合同(或协议)有效期止不能为空",
            trigger: "blur",
          },
        ],
      },
      // 审批弹窗
      approveDialog: false,
      approveForm: {
        driverId: "",
        driverName: "",
        approveStatus: "", // 1: 通过, 2: 拒绝
        approveReason: "",
      },
      approveRules: {
        approveStatus: [
          { required: true, message: "请选择审批结果", trigger: "change" },
        ],
        approveReason: [
          { required: true, message: "请填写审批原因", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询司机管理列表 */
    getList() {
      this.loading = true;
      listDriver(this.queryParams).then((response) => {
        this.driverList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        driverId: null,
        driverName: null,
        driverSex: null,
        driverPhone: null,
        registrationTime: null,
        cityId: null,
        bindVehicle: null,
        vehicleLevel: null,
        driverStatus: null,
        workStatus: null,
        userId: null,
        card: null,
        contractStartDate: null,
        contractEndDate: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.driverId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增司机";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const driverId = row.driverId || this.ids;
      getDriver(driverId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改司机管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.driverId != null) {
            updateDriver(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDriver(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const driverIds = row.driverId || this.ids;
      this.$modal
        .confirm('是否确认删除司机管理编号为"' + driverIds + '"的数据项？')
        .then(function () {
          return delDriver(driverIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "driver/driver/export",
        {
          ...this.queryParams,
        },
        `driver_${new Date().getTime()}.xlsx`
      );
    },

    /** 解冻按钮操作 */
    handleUnfreeze(row) {
      const driverId = row.driverId;
      this.$modal
        .confirm(`是否确认解冻司机"${row.driverName}"？`)
        .then(function () {
          // 这里需要替换为实际的解冻API
          return Promise.resolve();
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("解冻成功");
        })
        .catch(() => {});
    },

    /** 解约按钮操作 */
    handleTerminate(row) {
      const driverId = row.driverId;
      this.$modal
        .confirm(`是否确认与司机"${row.driverName}"解约？`)
        .then(function () {
          // 这里需要替换为实际的解约API
          return Promise.resolve();
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("解约成功");
        })
        .catch(() => {});
    },

    /** 详情按钮操作 */
    handleDetail(row) {
      // 跳转到司机详情页面，传递司机ID参数
      this.$router.push({
        path: "/detail",
        query: { driverId: row.driverId },
      });
    },
    /** 审批按钮操作 */
    handleApprove(row) {
      this.approveForm = {
        driverId: row.driverId,
        driverName: row.driverName,
        workStatus: "",
        approveReason: "",
      };
      this.approveDialog = true;
    },
    /** 提交审批 */
    submitApprove() {
      this.$refs["approveForm"].validate((valid) => {
        if (valid) {
          // 这里需要替换为实际的审批API
          updateDriverStatus(this.approveForm).then((response) => {
            this.$modal.msgSuccess("审批成功");
            this.approveDialog = false;
            this.getList();
          });
        }
      });
    },
  },
};
</script>
